package com.aliyun.messagemgt.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息导入导出监听器
 */

@Data
public class ExcelListener<T> extends AnalysisEventListener<T> {

    /**
     * 返回的数据集
     */
    private List<T> list = new ArrayList();


    //返回解析失败的数据行
    private List<String> erroinfomationList = new ArrayList<>();


    //一行一行读取excel内容
    @Override
    public void invoke(T data, AnalysisContext analysisContext) {
        System.out.printf("解析到一条数据:{%s}", JSON.toJSONString(data));
        list.add(data);
    }


    public void onException(Exception exception, AnalysisContext context) {
        System.out.printf("解析失败，但是继续解析下一行:{}", exception.getMessage());
        // 如果是某一个单元格的转换异常 能获取到具体行号
        // 如果要获取头的信息 配合invokeHeadMap使用
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            String erroinfo = "第{" +excelDataConvertException.getRowIndex()+"}行，第{"+"excelDataConvertException.getColumnIndex()"+"}列解析异常";
            erroinfomationList.add(erroinfo);
        }
    }

    //读取完成之后
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.printf("本次导入结束-------------------------");
    }

}
